import { commonAPI } from '@/api/api.js'

// 生成基于当前时间的随机文件路径
const generateRandomFilePath = (file) => {
  const url = file.name;
  const lastDotIndex = url.lastIndexOf('.');
  const extension = lastDotIndex !== -1 ? url.substring(lastDotIndex + 1) : 'png';

  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');

  // 生成随机字符串
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let randomStr = '';
  for (let i = 0; i < 14; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return `${year}/${month}/${randomStr}.${extension}`;
}

export const getFormData = ((file) => {
  return new Promise((resolve, reject) => {
    commonAPI.get('AlibabaCloud/credential').then(function (res) {
      if (res.code == 200) {
        const ossInfo = res.result;

        const imgUrl = generateRandomFilePath(file)

        const formData = {
          key: imgUrl,
          policy: ossInfo.policy,
          'x-oss-signature-version': ossInfo.x_oss_signature_version,
          'x-oss-credential': ossInfo.x_oss_credential,
          'x-oss-date': ossInfo.x_oss_date,
          'x-oss-signature': ossInfo.signature,
          'x-oss-security-token': ossInfo.security_token,
          success_action_status: '200'
        }

        resolve({ formData, host: ossInfo.host })
      } else {
        reject(new Error(res.message || '获取OSS凭证失败'))
      }
    }).catch(function (error) {
      reject(new Error('请求OSS凭证失败：' + error.message))
    })
  })
})

export const uploadFile = ((file) => {
  return new Promise((resolve, reject) => {
    // 首先获取OSS上传凭证和表单数据
    getFormData(file).then(function (ossData) {
      const { formData, host } = ossData

      // 创建FormData对象用于上传
      const uploadFormData = new FormData()

      // 添加OSS所需的表单字段
      Object.keys(formData).forEach(function (key) {
        uploadFormData.append(key, formData[key])
      })

      // 添加文件，注意file字段必须放在最后
      uploadFormData.append('file', file)

      // 使用axios上传到OSS
      const xhr = new XMLHttpRequest()

      xhr.open('POST', host, true)

      xhr.onload = function () {
        if (xhr.status === 200) {
          // 上传成功，返回文件URL
          const fileUrl = host + '/' + formData.key
          resolve({
            url: fileUrl,
            key: formData.key
          })
        } else {
          reject(new Error('上传失败，状态码：' + xhr.status))
        }
      }

      xhr.onerror = function () {
        reject(new Error('网络错误，上传失败'))
      }

      xhr.ontimeout = function () {
        reject(new Error('上传超时'))
      }

      // 设置超时时间
      xhr.timeout = 30000

      // 发送请求
      xhr.send(uploadFormData)

    }).catch(function (error) {
      reject(new Error('获取上传凭证失败：' + error.message))
    })
  })
})